from PyQt5.QtCore import QUrl, QProcess
from PyQt5.QtWidgets import QMessageBox

from qtThread import QtThread
from peopleSelect import PeopleSelect


# Qt 情景对抗实现的代码
class Confrontation(PeopleSelect):
    def __init__(self, mainWindow):
        super().__init__(mainWindow.ui.confrontation, mainWindow)
        self.process = QProcess()
        self.process.readyReadStandardOutput.connect(self.handle_stdout)
        self.process.readyReadStandardError.connect(self.handle_stderr)
        # 信号与槽连接
        self.ui.pushButton.clicked.connect(self.finishEdit)
        self.ui.btn_monitor.clicked.connect(self.monitor)
        self.ui.box_sceneName.currentIndexChanged.connect(self.sceneNameChange)
        self.ui.btn_training.clicked.connect(self.show_training)

    # 加载对抗训练页面内容
    def loadData(self):
        super().loadData()
        self.loadScene()
        # 创建子线程执行查询操作
        # self.loadSceneThread = QtThread(url =self.mainWindow.url + '/admin/atkdef_scene/data', cookies=self.session.cookies)
        # self.loadSceneThread.load_data.connect(self.loadScene)
        # self.loadSceneThread.start()
        # now = QDateTime.currentDateTime()
        # self.ui.dateTimeEdit.setDateTime(now)
        # self.ui.dateTimeEdit.setCalendarPopup(True)

    # 完成训练编辑
    def finishEdit(self):
        # 判断是否选择参训人员
        if not self.checkSelected():
            ERROR(u"请选择参训人员")
            return

        if self.ui.box_sceneName.currentIndex() == 0:
            ERROR(u'请选择情景名称')
            return

        if self.ui.box_trainName.currentText() == '':
            ERROR(u'请选择训练名称')
            return

        # 输出训练完成信息
        policeIds = self.getSelectedIds()
        if policeIds == None or policeIds == []:
            return

        self.ui.textBrowser.append(u"开始训练")
        names = self.getSelectedNames()
        strNames = ', '.join(list(map(str, names)))
        self.ui.textBrowser.append("警员 " + strNames + "已加入训练")
        self.ui.textBrowser.append("训练内容为：" + self.ui.box_sceneName.currentText())
        self.ui.textBrowser.append("训练情景为：" + self.ui.box_trainName.currentText())
        self.ui.textBrowser.append("")
        # if self.ui.box_sceneName.currentIndex() ==
        if self.ui.box_sceneName.currentIndex() == 1 and (
                self.ui.box_trainName.currentIndex() == 1
                or self.ui.box_trainName.currentIndex() == 2):
            if self.ui.box_trainName.currentIndex() == 1:
                setting_path = self.mainWindow.confrontation_training_setting
            elif self.ui.box_trainName.currentIndex() == 2:
                setting_path = self.mainWindow.confrontation_escape_setting
            with open(setting_path, mode='r') as f:
                lines = f.readlines()
            with open(setting_path, mode='w') as f:
                f.write('UserID ' + ','.join(policeIds) + '\n')
                if len(lines) != 3:
                    f.write('TNserverIP 127.0.0.1\n')
                else:
                    f.write('TNserverIP ' + lines[1].split(' ')[1])
                f.write('MainServerIP ' + self.mainWindow.url)

        if self.ui.box_sceneName.currentIndex() == 1:
            if self.ui.box_trainName.currentIndex() == 1:
                program_path = self.mainWindow.confrontation_training_path
            elif self.ui.box_trainName.currentIndex() == 2:
                program_path = self.mainWindow.confrontation_escape_path
            elif self.ui.box_trainName.currentIndex() == 3:
                program_path = self.mainWindow.confrontation_equipment_path
        elif self.ui.box_sceneName.currentIndex() == 2:
            program_path = self.mainWindow.confrontation_crew_path
        # 设置程序的工作目录，使得程序能够通过相对路径找到文件
        self.process.setWorkingDirectory(program_path[:program_path.rfind('\\') + 1])
        # 启动外部程序，参数是一个列表
        self.process.start(program_path, [])
        self.process.waitForFinished()
        return

    # if self.ui.box_sceneName.currentText() == u'单人训练':
    #     self.mainWindow.external.load_program(self.mainWindow.confrontation_single_path,
    #                                           self.mainWindow.confrontation_single_name)
    #     self.mainWindow.ui.stackedWidget.setCurrentWidget(self.mainWindow.ui.external.page_widgets)
    # elif self.ui.box_sceneName.currentText() == u'多人训练':
    #     self.mainWindow.external.load_program(self.mainWindow.confrontation_crew_path,
    #                                           self.mainWindow.confrontation_crew_name)
    #     self.mainWindow.ui.stackedWidget.setCurrentWidget(self.mainWindow.ui.external.page_widgets)

    def sceneNameChange(self):
        # 根据选择的情景名称，动态改变可以选择的训练项
        sceneName = self.ui.box_sceneName.currentText()
        index = self.ui.box_sceneName.currentIndex()
        self.ui.box_trainName.clear()
        self.ui.box_trainName.addItem('')
        # if sceneName == '':
        #     return
        # self.ui.box_trainName.addItems(list(self.scenes_trains_ids[sceneName].keys()))
        if index == 0:
            return
        elif index == 1:
            self.ui.box_trainName.addItem('执法训练')
            self.ui.box_trainName.addItem('体验式灾害逃生与处置训练')
            self.ui.box_trainName.addItem('典型器械使用虚拟训练')
        elif index == 2:
            self.ui.box_trainName.addItem('多人角色扮演攻防训练')

    # 跳转到监控页面的实现函数
    def monitor(self):
        self.mainWindow.ui.web.browser.load(QUrl(self.mainWindow.url + '/admin/scene_homepage/'))
        self.mainWindow.ui.stackedWidget.setCurrentWidget(self.mainWindow.ui.web.page_widgets)

    # 子线程获取信息后执行此函数，显示可供选择的情景
    def loadScene(self, text):
        data = text['data']
        self.ui.box_sceneName.clear()
        # 从后端获取所有的训练情景以及训练项，并记录
        self.scenes_trains_ids = dict()
        for d in data:
            if (self.scenes_trains_ids.get(d['scene_type']) == None):
                self.scenes_trains_ids[d['scene_type']] = {d['train_type']: d['id']}
            else:
                self.scenes_trains_ids[d['scene_type']].update({d['train_type']: d['id']})

        self.ui.box_sceneName.addItem('')
        self.ui.box_sceneName.addItems(list(self.scenes_trains_ids.keys()))

    def loadScene(self):
        self.ui.box_sceneName.clear()
        self.ui.box_sceneName.addItem('')
        self.ui.box_sceneName.addItem('单人训练')
        self.ui.box_sceneName.addItem('多人训练')

    def show_training(self):
        # 设置程序的工作目录，使得程序能够通过相对路径找到文件
        self.process.setWorkingDirectory(
            self.mainWindow.confrontation_model_path[:self.mainWindow.confrontation_model_path.rfind('\\') + 1])
        # 启动外部程序，参数是一个列表
        self.process.start(self.mainWindow.confrontation_model_path,[])
        self.process.waitForFinished()
        # self.mainWindow.external.load_program(self.mainWindow.confrontation_training_path,
        #                                       self.mainWindow.confrontation_training_name)
        # self.mainWindow.ui.stackedWidget.setCurrentWidget(self.mainWindow.ui.external.page_widgets)

    def handle_stdout(self):
        print(self.process.readAllStandardOutput())

    # 打印调用的外部程序的stderr信息
    def handle_stderr(self):
        print(self.process.readAllStandardError())


def ERROR(message):
    msg_box = QMessageBox(QMessageBox.Critical, '错误', message)
    msg_box.exec_()
